import cv2
import numpy as np

# 读取图像，并将其转换为灰度图
img = cv2.imread('images/demo2.png', 0)
# 定义阈值和最大值
threshold_value = 127
max_value = 255
# 应用不同类型的阈值操作
_, thresh_binary = cv2.threshold(img, threshold_value, max_value, cv2.THRESH_BINARY)
_, thresh_binary_inv = cv2.threshold(img, threshold_value, max_value, cv2.THRESH_BINARY_INV)
_, thresh_trunc = cv2.threshold(img, threshold_value, max_value, cv2.THRESH_TRUNC)
_, thresh_tozero = cv2.threshold(img, threshold_value, max_value, cv2.THRESH_TOZERO)
_, thresh_tozero_inv = cv2.threshold(img, threshold_value, max_value, cv2.THRESH_TOZERO_INV)
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Binary Threshold', thresh_binary)
cv2.imshow('Binary Inverse Threshold', thresh_binary_inv)
cv2.imshow('Truncate Threshold', thresh_trunc)
cv2.imshow('ToZero Threshold', thresh_tozero)
cv2.imshow('ToZero Inverse Threshold', thresh_tozero_inv)

# 等待按键输入并关闭窗口
cv2.waitKey(0)
cv2.destroyAllWindows()
